package mynet

import (
	"sync"
)

type roomManager struct {
	rooms    map[string]IUserRoom
	roomLock sync.Mutex
}

func (this *roomManager) CreateOneRoom(usernumber string) {
	_, ok := this.rooms[usernumber]
	if ok {
		return
	}
	this.roomLock.Lock()
	defer this.roomLock.Unlock()
	this.rooms[usernumber] = GetNewUserRoom(usernumber)
}

func (this *roomManager) GetAllRoom() []IUserRoom {
	rooms := make([]IUserRoom, 0, len(this.rooms))
	for _, room := range this.rooms {
		rooms = append(rooms, room)
	}
	return rooms
}

func (this *roomManager) DelRoom(usernumber string) {
	this.roomLock.Lock()
	defer this.roomLock.Unlock()
	delete(this.rooms, usernumber)
}

func (this *roomManager) FindRoom(usernumber string) IUserRoom {
	return this.rooms[usernumber]
}

func (this *roomManager) UserJoin(userRoomNumber string, usernumber string, user IConnection) {
	room := this.rooms[userRoomNumber]
	if !room.CheckIsFull() {
		room.Join(usernumber, user)
	}
}

func (this *roomManager) GetRoomUsers(userRoomNumber string, usernumber string) []string {
	if this.rooms[userRoomNumber] != nil {
		return this.rooms[userRoomNumber].GetAllUserNumber()
	}
	return nil
}

func (this *roomManager) UserDel(userRoomNumber string, usernumber string) {
	this.rooms[userRoomNumber].Del(usernumber)
}

func GetNewRoomManager() IRoomManager {
	return &roomManager{
		rooms: make(map[string]IUserRoom),
	}
}

//当删除一个东西的时候有可能是这种情况，就是这个地方已经删除了，而另外一个地方的应用却依然存在，空指针异常，需要考虑
